from info import constants
from info.models import News
from . import news_blue
from flask import session, render_template, current_app, g, jsonify, request
from info.utils.commons import login_required
from info.utils.response_code import RET
# 主页路由
@news_blue.route('/')
@login_required
def index():
    # 获取用户数据
    user = g.user
    # 获取分页信息
    from info.models import Category,News
    try:
        category_list = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询分类信息失败")
    if not category_list:
        return jsonify(errno=RET.DATAERR, errmsg="无分类信息")
    category_info=[]
    for category in category_list:
        category_info.append(category.to_dict())
    # 获取排行信息
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS-4)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询排行信息失败")
    if not news_list:
        return jsonify(errno=RET.DATAERR,errmsg='无新闻排行数据')
    news_click_list = []
    for news in news_list:
        news_click_list.append(news.to_dict())
    data = {
        "user_info" : user.to_dict() if user else None,
        "category_info" : category_info,
        "news_click_list" : news_click_list
    }
    return render_template('news/index.html',data=data)

# logo加载
@news_blue.route('/favicon.ico')
def favicon():
    return current_app.send_static_file('news/favicon.ico')


# 加载主页新闻数据
@news_blue.route('/news_list')
def news_list():
    cid = request.args.get('cid', '1')
    page = request.args.get('page', '1')
    per_page = request.args.get('per_page', '10')
    # 转换参数的数据类型
    try:
        cid, page, per_page = int(cid), int(page), int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数格式错误')
    # 定义容器，存储查询的过滤条件
    filters = []
    # 判断分类id如果不是最新
    if cid > 1:
        filters.append(News.category_id == cid)
    # 使用过滤条件查询mysql，按照新闻发布时间排序
    print(filters)
    try:
        # *filters表示python中拆包，News.category_id==cid，*filters里面存储的是sqlalchemy对象
        # 在python中测试添加的数据为True或False
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询新闻数据失败')
# 获取分页后的数据
    news_list = paginate.items
    total_page = paginate.pages
    current_page = paginate.page
    # 定义容器，存储查询到的新闻数据
    news_dict_list = []
    for news in news_list:
        news_dict_list.append(news.to_dict())
    data = {
        'news_dict_list':news_dict_list,
        'total_page':total_page,
        'current_page':current_page
    }
    # 返回数据
    return jsonify(errno=RET.OK,errmsg='OK',data=data)

